//
//  ChooseCityViewController.m
//  ChooseLocation
//
//  Created by Apple on 14/11/25.
//  Copyright (c) 2014年 Apple. All rights reserved.
//

#import "ChooseCityViewController.h"
#import "MKFirstTableViewCell.h"
#import "MKSecondTableViewCell.h"
#import "MKThirdTableViewCell.h"
#import "MKHandleCityData.h"
#import "MKCity.h"
#import "MKViewController.h"
#import <CoreLocation/CoreLocation.h>

@interface ChooseCityViewController ()<MKSecondTableViewCellDelegate, CLLocationManagerDelegate>

@property (nonatomic, strong) NSMutableArray * originalDataArray; // 原始数据城市
@property (nonatomic, strong) NSMutableArray * letterArray; // 每个城市的第一个字母
@property (nonatomic, strong) NSMutableArray * fixArray; // 里面是每个字母对应的城市
@property (nonatomic, strong) NSMutableArray * pinyinArray; // 拼音

@property (nonatomic, strong) NSString * selectString; // 选中那个城市

@property (nonatomic, strong) CLLocationManager * locationManager;
@property (nonatomic, strong) CLGeocoder * geocoder;

@end

@implementation ChooseCityViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.letterArray = [NSMutableArray array];
        self.pinyinArray = [NSMutableArray array];
        self.fixArray = [NSMutableArray array];
        self.originalDataArray = [NSMutableArray array];
        self.selectString = @"";
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    NSString * titleString = [[NSUserDefaults standardUserDefaults] objectForKey:@"showCity"];
    self.navigationItem.title = [NSString stringWithFormat:@"当前城市-%@", titleString];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"刷新" style:UIBarButtonItemStyleDone target:self action:@selector(refreshLocation:)];
    
    self.selectString = titleString;
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    
    [self handleDataOnOtherThread];
    
}

// 刷新定位
- (void)refreshLocation:(UIBarButtonItem *)sender
{
    [self startLocation];
}

- (void)startLocation
{
    // 开始定位
    if ([[UIDevice currentDevice] systemVersion].floatValue >= 8.0) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [self startTrackingLocation];
    } else {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 1;
        [_locationManager startUpdatingLocation];
    }
    
}

// iOS 8.0 之后的定位
- (void)startTrackingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (status == kCLAuthorizationStatusNotDetermined) {
        [_locationManager requestWhenInUseAuthorization];
    } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorizedAlways) {
        [_locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    [_locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 创建一个定位对象
    CLLocation * theLocation = [[CLLocation alloc] initWithLatitude:manager.location.coordinate.latitude longitude:manager.location.coordinate.longitude];
    _geocoder = [[CLGeocoder alloc] init];
    [_geocoder reverseGeocodeLocation:theLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        if (placemarks.count > 0) {
            CLPlacemark * placeMark = [placemarks objectAtIndex:0];
            NSString * city = placeMark.locality; // 城市
            NSString * admiCity = placeMark.administrativeArea; // 直辖市
            
            BOOL isCityNil = [city isEqual:@""] || city == nil;
            BOOL isAdmiCityNil = [admiCity isEqual:@""] || admiCity == nil;
            
            if (!(isCityNil && isAdmiCityNil)) {
                // 当城市或直辖市存在，停止定位
                [manager stopUpdatingLocation];
                
                NSString * rcity;
                
                if (!isCityNil) {
                    rcity = city;
                } else if (!isAdmiCityNil) {
                    rcity = admiCity;
                }
                
                MKHandleCityData * handleData = [[MKHandleCityData alloc] init];
                NSString * cityString = [handleData cityFormatWithString:rcity];
                
                // 存储定位到的城市
                [[NSUserDefaults standardUserDefaults] setObject:cityString forKey:@"city"];
                [[NSUserDefaults standardUserDefaults] synchronize];

            }
        }
    }];
}


//- (void)viewDidDisappear:(BOOL)animated
//{
//    self.selectCity(self.selectString);
//}
//
//
//- (void)sendSelectCity:(SelectedCity)blockCity
//{
//    self.selectCity = blockCity;
//}


- (void)handleDataOnOtherThread
{
    // 开辟新的线程来处理数据
    dispatch_queue_t concurrentQueue = dispatch_queue_create("com.chooseLocation.handleData", DISPATCH_QUEUE_CONCURRENT);
    MKHandleCityData * hanleCityData = [[MKHandleCityData alloc] init];
    dispatch_async(concurrentQueue, ^{
        
        self.originalDataArray = [NSMutableArray arrayWithObjects:@"北京站", @"成都站", @"重庆站", @"长沙站", @"大连站", @"哈尔滨站", @"杭州站", @"合肥站", @"济南站", @"上海站", @"沈阳站", @"石家庄", @"天津站", @"武汉站", @"西安站", @"郑州站", nil];
        
        NSData * sortData = [[NSUserDefaults standardUserDefaults] objectForKey:@"sortArray"];
        NSMutableArray * resultArray = [NSMutableArray array];
        resultArray = [NSKeyedUnarchiver unarchiveObjectWithData:sortData];
        if (resultArray.count == 0) {
            resultArray = [NSMutableArray arrayWithArray:[hanleCityData changeHanZiToPinYinWithArray:self.originalDataArray]];
        }
        
        MKCity * city = [[MKCity alloc] init];
        [self.letterArray addObjectsFromArray:[resultArray objectAtIndex:0]];
        [self.fixArray addObjectsFromArray:[resultArray objectAtIndex:1]];
        [self.pinyinArray addObjectsFromArray:[resultArray objectAtIndex:2]];
        
        [self.letterArray insertObject:@"!" atIndex:0];
        [self.letterArray insertObject:@"#" atIndex:0];
        [self.letterArray insertObject:@"!" atIndex:self.letterArray.count];
        [self.letterArray insertObject:@"#" atIndex:self.letterArray.count];
        
        
        [self.fixArray insertObject:city atIndex:0];
        [self.fixArray insertObject:city atIndex:0];
        [self.fixArray insertObject:city atIndex:self.fixArray.count];
        [self.fixArray insertObject:city atIndex:self.fixArray.count];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
        
    });
    
}

#pragma mark - tableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 50.0;
    }
    
    if (indexPath.section == 1) {
        return 100.0;
    }
    
    return 50.0;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.letterArray.count != 0) {
        return self.letterArray.count;
    }
    return 2;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString * titleString;
    if (section == 0) {
        titleString = @"定位城市";
    }
    
    if (section == 1) {
        titleString = @"热门城市";
    }
    
    if (self.letterArray.count != 0) {
        if (section == self.letterArray.count - 2) {
            titleString = @"其他";
        }
        
        if (section >= 2 && section < self.letterArray.count - 2) {
            titleString = [self.letterArray objectAtIndex:section];
        }
    }
    
    return titleString;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1 || section == self.letterArray.count - 1 || section == self.letterArray.count - 2) {
        return 1;
    } else {
        NSMutableArray * array = [self.fixArray objectAtIndex:section];
        return array.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == self.letterArray.count - 1) {
        return 0.1;
    }
    return 25.0;
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    // 索引的实现
    return self.letterArray;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString * cellID = @"firstCellId";
        MKFirstTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[MKFirstTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.firstTextLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if (indexPath.section == 1) {
        static NSString * cellID = @"secondCellId";
        MKSecondTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[MKSecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        cell.delegate = self;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    
    if (indexPath.section > 1) {
        static NSString * cellID = @"thirdCellId";
        MKThirdTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (cell == nil) {
            cell = [[MKThirdTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.section == self.letterArray.count - 2) {
            
            cell.showTextLabel.text = @"为什么没有我这里，求分站?";
            cell.showTextLabel.textAlignment = NSTextAlignmentLeft;
            
        } else if (indexPath.section == self.letterArray.count - 1) {
            
            cell.showTextLabel.text = [NSString stringWithFormat:@"共计：%d个城市站点", self.originalDataArray.count];
            cell.showTextLabel.textAlignment = NSTextAlignmentCenter;
            
        } else {
            NSArray * letterArray = [self.fixArray objectAtIndex:indexPath.section]; // 对应字母所含城市数组
            MKCity * city = [letterArray objectAtIndex:indexPath.row];
            cell.showTextLabel.text = city.cityName;
            cell.showTextLabel.textAlignment = NSTextAlignmentLeft;
        }
        return cell;
    }
    
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section > 1 && indexPath.section < self.letterArray.count - 2) {
        MKThirdTableViewCell * cell = (MKThirdTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        self.selectString = cell.showTextLabel.text;
        [self storeSelectCity:self.selectString];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)selectWhichView:(NSInteger)num
{
    NSString * cityString = @"";
    switch (num) {
        case 0:
        {
            cityString = @"北京站";
        }
            break;
        case 1:
        {
            cityString = @"天津站";
        }
            break;
        case 2:
        {
            cityString = @"上海站";
        }
            break;
        case 3:
        {
            cityString = @"西安站";
        }
            break;
        case 4:
        {
            cityString = @"武汉站";
        }
            break;
        case 5:
        {
            cityString = @"成都站";
        }
            break;
        default:
            break;
    }
    self.selectString = cityString;
    [self storeSelectCity:self.selectString];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)storeSelectCity:(NSString *)city
{
    [[NSUserDefaults standardUserDefaults] setObject:city forKey:@"showCity"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
